<?php
namespace app\admin\controller;

class Qiniu extends Auth{

	public function __construct()
	{
		parent::__construct();
		$this->qiniu_get_info = unserialize(file_get_contents('qiniu.php'));

	}
	
	/**
	* 获取上传token
	*
	**/
	public function uptoken()
	{

	    //这里重命名文件名，实例化上传类
        
        Vendor('qiniu.autoload');
		// 引入鉴权类
        Vendor('qiniu.Qiniu.Auth');
		// 引入上传类
        Vendor('qiniu.Qiniu.Storage.UploadManager');
        
		$accessKey = $this->qiniu_get_info['ak'];
		$secretKey = $this->qiniu_get_info['sk'];
		 // 要上传的空间
		$bucket = $this->qiniu_get_info['bucket'];
		// 构建鉴权对象
		$auth = new \Qiniu\Auth($accessKey,$secretKey);
		//构建上传策略
		$policy = array(
		    "saveKey" => '$(year)$(mon)$(day)$(hour)$(min)$(sec)',
		    "callbackUrl" => "http://".$_SERVER['SERVER_NAME']."/admin/qiniu/callback.html",
		    "callbackBody" => '{"savename":"$(key)","filesize":"$(fsize)","savepath":"$(x:url)","ext":"$(ext)"}',
		   // "returnUrl" => "http://www.baidu.com/",
		);
       
		// 生成上传 Token
		$upToken = $auth->uploadToken($bucket,null, 3600, $policy);
		$url = $this->qiniu_get_info['url'];

		$info = array('token'=>$upToken,'url'=>$url);

		header('Access-Control-Allow-Origin:*');
		return json_encode($info);		

	}

	/**
	* 回调地址
	*
	**/

   public function callback()
   {

		Vendor('qiniu.autoload');
		Vendor('qiniu.Qiniu.Auth');

		$accessKey = $this->qiniu_get_info['ak'];
		$secretKey = $this->qiniu_get_info['sk'];
		$auth = new \Qiniu\Auth($accessKey, $secretKey);

		//获取回调的body信息
		$callbackBody = file_get_contents('php://input');
		$body = json_decode($callbackBody);
        file_put_contents("yanli.php",$body);

		header('Content-Type: application/json');
		$resp = array('ret' => 'success');
		echo json_encode($body);


   }

	/**
	* 删除指定图片
	*
	**/

	 public function del($name)
	 {

	   Vendor('qiniu.autoload');
	   Vendor('qiniu.Qiniu.Auth');
	   Vendor('qiniu.Qiniu.Storage.UploadManager');
	   Vendor('qiniu.Qiniu.Storage.BucketManager');

		$accessKey = $this->qiniu_get_info['ak'];
		$secretKey = $this->qiniu_get_info['sk'];
	 // 要删除的空间
	$bucket = $this->qiniu_get_info['bucket'];
	// 构建鉴权对象
	$auth = new \Qiniu\Auth($accessKey, $secretKey);
	  //初始化BucketManager
	$bucketMgr = new \Qiniu\Storage\BucketManager($auth);

	//这个key在你空间中存在
	$key = $name;


	//删除$bucket 中的文件 $key
	 $err = $bucketMgr->delete($bucket, $key);

	  if ($err !== null) {
	      var_dump($err);
	  } else {
	     return $this->success('删除成功');
	  }




 }












	
	
	
}
